<template>
  <el-form :inline="true" :model="state" class="demo-form-inline">
    <el-form-item label="流水号">
      <el-input v-model="state.lsh" placeholder="请输入流水号" clearable />
    </el-form-item>
    <el-form-item label="文件名">
      <el-input v-model="state.wjm" placeholder="请输入文件名" clearable />
    </el-form-item>
    <el-form-item label="员工号">
      <el-input v-model="state.ygh" placeholder="请输入员工号" clearable />
    </el-form-item>
    <el-form-item label="员工名">
      <el-input v-model="state.ygm" placeholder="请输入员工号" clearable />
    </el-form-item>
    <el-form-item label="机构号">
      <el-input v-model="state.jgh" placeholder="请输入机构号" clearable />
    </el-form-item>
    <el-form-item label="机构码">
      <el-input v-model="state.jgm" placeholder="请输入机构码" clearable />
    </el-form-item>
    <el-form-item label="机构名">
      <el-input v-model="state.jgn" placeholder="请输入机构名" clearable />
    </el-form-item>
    <el-form-item label="上级机构">
      <el-input v-model="state.sj" placeholder="请输入上级机构" clearable />
    </el-form-item>
    <el-form-item label="通话时间">
    <el-date-picker
        v-model="state.thdate"
        type="datetimerange"
        start-placeholder="通话开始日期"
        end-placeholder="通话结束日期"
        format="YYYY-MM-DD HH:mm:ss"
        value-format="YYYY-MM-DD HH:mm:ss"
        date-format="YYYY/MM/DD ddd"
        time-format="A hh:mm:ss"
    />
    </el-form-item>
    <el-form-item label="操作人">
      <el-input v-model="state.czr" placeholder="请输入操作人" clearable />
    </el-form-item>
    <el-form-item label="操作时间">
      <el-date-picker
          v-model="state.czdate"
          type="datetimerange"
          start-placeholder="操作开始日期"
          end-placeholder="操作结束日期"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          date-format="YYYY/MM/DD ddd"
          time-format="A hh:mm:ss"
      />
    </el-form-item>

    <el-form-item label="上传类型">
      <el-select
          v-model="state.sctype"
          placeholder="上传类型"
          clearable
      >
        <el-option label="音频" value="音频" />
        <el-option label="视频" value="视频" />
      </el-select>
    </el-form-item>
    <el-form-item label="场景类型">
      <el-select
          v-model="state.cjtype"
          placeholder="场景类型"
          clearable
      >
        <el-option label="场景1" value="场景1" />
        <el-option label="场景2" value="场景2" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" :icon="Search" @click="Seach">搜索</el-button>
    </el-form-item>
    <el-form-item>
      <el-button :icon="RefreshRight" @click="clear()">重置</el-button>
    </el-form-item>


  </el-form>

  <el-form :inline="true" >
  <el-form-item>

      <el-upload
          :auto-upload="false"
          :on-change="handleChange"
          :on-success="handleSuccess"
          :on-error="handleError"
          :before-upload="beforeUpload"
          accept="audio/*"
          :limit="1"
          :on-exceed="handleExceed"
      >
        <el-button type="primary" :icon="UploadFilled" :disabled="buttonAudio">点击上传音频</el-button>
      </el-upload>

  </el-form-item>
  <el-form-item>
      <el-upload
          :auto-upload="false"
          :on-change="handleChangeVideo"
          :on-success="handleSuccess"
          :on-error="handleError"
          :before-upload="beforeUploadVideo"
          accept="video/*"
          :limit="1"
          :on-exceed="handleExceed"
      >
        <el-button type="primary"  :icon="UploadFilled"  :disabled="buttonVideo">点击上传视频</el-button>
      </el-upload>
  </el-form-item>
    <el-form-item>
      <el-button type="primary"  :icon="UploadFilled" :disabled="buttonexport" @click="exportFile">导出</el-button>
    </el-form-item>
<!--    <el-form-item>-->
<!--      <el-button type="primary"  :icon="UploadFilled" :disabled="buttonexport" @click="exportToExcel">转换为excel</el-button>-->
<!--    </el-form-item>-->


  </el-form>

  <el-table :data="state2.tableData" style="width: 100%"
            @selection-change="handleSelectionChange"
            v-model:selection="selectedRows">
    <el-table-column type="selection" width="55" />
    <el-table-column fixed prop="lsh" label="流水号"  show-overflow-tooltip />
    <el-table-column prop="wjm" label="文件名"   show-overflow-tooltip/>
    <el-table-column prop="ygh" label="员工号"  show-overflow-tooltip />
    <el-table-column prop="ygm" label="员工名"  show-overflow-tooltip/>
    <el-table-column prop="jgh" label="机构号"  show-overflow-tooltip/>
    <el-table-column prop="jgm" label="机构码"  show-overflow-tooltip/>
    <el-table-column prop="jgn" label="机构名"  show-overflow-tooltip/>
    <el-table-column prop="sj" label="上级机构"  show-overflow-tooltip/>
    <el-table-column prop="thdatestart" label="通话开始日期" />
    <el-table-column prop="thdateend" label="通过结束日期" />
    <el-table-column prop="czr" label="操作人" />
    <el-table-column prop="czdatestart" label="操作开始日期" />
    <el-table-column prop="czdateend" label="操作结束日期" />
    <el-table-column prop="sctype" label="上传类型" />
    <el-table-column prop="cjtype" label="场景类型" />
  </el-table>
</template>

<script lang="ts" setup>
import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';
import { onMounted, onUnmounted, reactive, ref } from 'vue'
import request from "@/utils/request";
import { RefreshRight, Search, UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useAccount } from '@/pinia/modules/account';
// const { userinfo } = storeToRefs(useAccount())

const account = useAccount()
let buttonAudio=ref(false);
let buttonVideo=ref(false);
let buttonexport=ref(false);
const state=reactive({
  lsh:'',
  wjm:'',
  ygh:'',
  ygm:'',
  jgh:'',
  jgm:'',
  jgn:'',
  sj:'',
  thdate:[],
  czr:'',
  czdate:[],
  sctype:'',
  cjtype:''
})
const selectedRows = ref([]);

// 处理选择变化的事件
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
  console.log('Selected rows:', selectedRows.value);
};

const exportFile=()=>{

  if (selectedRows.value.length===0) {
    ElMessage.warning('选择的导出文件为空 请至少选择一个文件');
    return;
  }
  let data=selectedRows.value.map((data)=>{
    return {
      wjm:data.wjm,
      sctype:data.sctype,
    }
  })
  data.forEach((filenameAndtype) => {
    downloadFile(filenameAndtype);
  });
}

const downloadFile = async (filename) => {

  // try {
        await request.post("/AVideo/export", filename,{
      responseType: 'arraybuffer'
    }).then((response) => {
      const blob = new Blob([response.data]);
      console.log(response)

      const a = document.createElement("a");
      const href = window.URL.createObjectURL(blob); // 下载链接
      a.href = href;
      a.download = decodeURI(
          response.headers["content-disposition"].split(";")[1].split("=")[1]
      ); // 获取后台设置的文件名称
      document.body.appendChild(a);
      a.click(); // 点击下载
      document.body.removeChild(a); // 下载完成移除元素
      window.URL.revokeObjectURL(href); // 释放掉blob对象
    });

}
const state2=reactive({
  tableData:[],
})
//将表单导出为excel表
const exportToExcel=()=>{
  const tableData = state2.tableData; // 假设这是你的表格数据
  const ws = XLSX.utils.json_to_sheet(tableData);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  XLSX.writeFile(wb, 'exported_data.xlsx');
}

const Seach=()=>{
  load();
}
const load=async ()=>{
  const audio={
    lsh:state.lsh,
    wjm:state.wjm,
    ygh:state.ygh,
    ygm:state.ygm,
    jgh:state.jgh,
    jgm:state.jgm,
    jgn:state.jgn,
    sj:state.sj,
    thdatestart:state.thdate[0],
    thdateend:state.thdate[1],
    czr:state.czr,
    czdatestart:state.czdate[0],
    czdateend:state.czdate[1],
    sctype:state.sctype,
    cjtype:state.cjtype
  }
  await request.post('/audio/select',audio).then(res=>{
    state2.tableData=res.data
    console.log(state2.tableData)
  })
}
onMounted(()=>{
  if(account.userinfo.yhlx===1){
    buttonAudio.value=true
    buttonVideo.value=true
    buttonexport.value=true
  }
  load();
})
const filescan=async ()=>{
  await request.post('/scan/file').then((res)=>{
    if(res.data==='成功'){
      ElMessage.success('定时扫描文件并且更新成功')
    }else{
      ElMessage.error('定时扫描文件并且更新失败')
    }
    load()
  })
}
onMounted(() => {
  const interval = setInterval(filescan, 5000*2)//2分钟一刷新
  // 清除定时器
  onUnmounted(() => {
    clearInterval(interval)
  })
})
const clear=()=>{
  state.lsh=''
  state.wjm=''
  state.ygh=''
  state.ygm=''
  state.jgh=''
  state.jgm=''
  state.jgn=''
  state.sj=''
  state.thdate=[],
  state.czr=''
  state.czdate=[],
  state.sctype=''
  state.cjtype=''
}

let file = ref(null);

const handleChange = async (fileObj, fileList) => {
  file.value = fileObj.raw;
  if (!file.value) {
    ElMessage.error('请选择一个文件');
    return;
  }

  const formData = new FormData();
  formData.append('file', file.value);
  try {
    const response = await request.post('/audiof/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(res=>{
      console.log("音频数据返回值"+res.data)
    });
    load()
    handleSuccess();

  } catch (error) {
    handleError();
  }

};

const handleSuccess = () => {
  ElMessage({
    message: '上传成功！',
    type: 'success',
  })
};

const handleError = () => {
  ElMessage.error('上传失败')
};

const beforeUpload = (file) => {
  const isAudio = file.type.startsWith('audio/');
  if (!isAudio) {
    ElMessage.error('只能上传音频文件');
    return false;
  }
  return true;
};

const handleExceed = (files, fileList) => {
  ElMessage.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
};

const handleChangeVideo= async (fileObj, fileList) => {
  file.value = fileObj.raw;
  if (!file.value) {
    ElMessage.error('请选择一个文件');
    return;
  }

  const formData = new FormData();
  formData.append('file', file.value);
  try {
    const response = await request.post('video/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(res=>{
      console.log("视频数据返回值"+res.data)
    });
    load()
    handleSuccess();

  } catch (error) {
    handleError();
  }

};
const beforeUploadVideo= (file) => {
  const isAudio = file.type.startsWith('video/');
  if (!isAudio) {
    ElMessage.error('只能上传视频文件');
    return false;
  }
  return true;
};




</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
